<?php
use Workerman\Worker;
require_once __DIR__ . '/Workerman/Autoloader.php';

// 注意：这里与上个例子不同，使用的是websocket协议
$ws_worker = new Worker("websocket://0.0.0.0:2000");

// 启动4个进程对外提供服务
$ws_worker->count = 1;

//存储在线用户
$user_arr = ['red'];

//在线人数
$user_count = 0;

//当有客户端连接触发的函数
$ws_worker->onConnect = function($connection)
{
	global $user_count,$ws_worker;
	$user_count++;
	foreach($ws_worker->connections as $con){
		$send_data = json_encode([
			'type' => 'online_user_count',
			'online_user_count' => $user_count
		]);
		$con->send($send_data);
	}
};

// 客户端发来消息时回调函数
$ws_worker->onMessage = function($connection, $data)use($ws_worker)
{
	$data_arr = json_decode($data,1);
	//登录
	if($data_arr['type'] =='login'){
		//广播新用户加入
		//保存用户名
		$connection->username = $data_arr['username'];
		$send_data = json_encode([
			'type' => 'new_user_login',
			'username' => $data_arr['username']
		]);
		//遍历当前连接的所有客户端  
		//$ws_worker->connections为所有连接的客户端
		foreach($ws_worker->connections as $con)
		{
			$con->send($send_data);
		}	
	}
	
	//发送消息
	if($data_arr['type'] == 'send_msg'){
		//广播新用户加入
		//遍历当前连接的所有客户端  
		foreach($ws_worker->connections as $con)
		{
			$send_data = [
				'type' => 'new_msg',
				'username' => $data_arr['username'],
				'content' => $data_arr['content'],
				'my_msg' => 0
			];
		
			if($connection->id==$con->id){
				$send_data['my_msg'] = 1;
			}
			$con->send(json_encode($send_data));
		}	
	}
};

//断开连接时
$ws_worker->onClose = function($connection)
{
	global $user_count,$ws_worker;
	$user_count--;
	foreach($ws_worker->connections as $con){
		//给用户广播用户退出
		$send_data = json_encode([
		 	'type' => 'user_on_close',
			'username' => $connection->username
		]);
		$con->send($send_data);
		
		//统计在线人数
		$online_user_count_send_data = json_encode([
			'type' => 'online_user_count',
			'online_user_count' => $user_count
		]);
		$con->send($online_user_count_send_data);
	}
};

// 运行worker
Worker::runAll();

